<?php

namespace StudyBuddy;

/**
 *
 * Class for rendering block with
 * tags that user is following
 * and also adding another block
 * of "you both follow these tags"
 * if Viewer following some of the same tags
 */
class UserFollowedTags extends StudyBuddyObject {
    /**
     * Maximum tags to show in user tags block
     * A very active user can have hundreds of tags, we
     * want to show only the 60
     * most popular tags for this user
     *
     *
     * @var int
     */
    const MAX_TO_SHOW = 40;

    /**
     * 
     * Get block with links to tags that User is following
     * and also possibly a block on tags that both Viewer and User
     * are following
     * 
     * @param Registry $oRegistry
     * @param User $oUser
     * 
     * @return string html
     */
    public static function get(Registry $oRegistry, User $oUser) {
        $aUserTags = $oUser['a_f_t'];
        if (empty($aUserTags)) {
            return '';
        }

        if (count($aUserTags) > self::MAX_TO_SHOW) {
            $aUserTags = \array_slice($aUserTags, 0, self::MAX_TO_SHOW);
        }

        /**
         * @todo Translate string
         */
        $blockTitle = $oUser->getDisplayName() . ' is following these tags';
        $tags = $commonTags = '';

        $tags = \tplTagLink::loop($aUserTags, false);

        d('tags: ' . $tags);

        /**
         * If Viewer is not the same user as user whose profile
         * being viewer then attempt to get the 'common' tags
         * that both viewer and user are following
         */
        if ($oUser->getUid() !== $oRegistry->Viewer->getUid()) {
            $commonTags = self::getCommonTags($aUserTags, $oRegistry->Viewer['a_f_t']);
        }

        $vals = array('count' => $blockTitle, 'label' => 'tag', 'tags' => $tags);

        $ret = \tplUserTags::parse($vals);

        return $ret . $commonTags;
    }

    /**
     * Get array of tags that both User and Viewer following
     * and return parsed block 'You both follow'
     *
     * @param array $userTags
     * @param array $viewerTags
     *
     * @return string html block or empty String if there are
     * no common tags
     */
    protected static function getCommonTags(array $userTags, array $viewerTags) {

        $aCommon = \array_intersect($userTags, $viewerTags);
        if (empty($aCommon)) {
            return '';
        }

        $tags = \tplTagLink::loop(array_values($aCommon), false);
        /**
         * @todo translate string 'You both follow'
         *
         */
        $vals = array('count' => 'You both follow', 'label' => 'tag', 'tags' => $tags);

        return \tplUserTags::parse($vals);
    }

}
